<?php

/**
 * 函数定义
 * User: jiang
 * Date: 16/6/5
 * Time: 16:05
 */

/**
 * 对象转换成数组
 * @param $object
 * @return mixed
 */
function objToArray($object)
{
    if(empty($object)){
        return $object;
    }
    return json_decode(json_encode($object), true);
}

/**
 * 数组转换父子树形结果
 * @param $id
 * @param $data
 * @return array
 */
function parentSons($id, $data)
{
    $sons = [];
    foreach($data as $key=>$value)
    {
        if($value['parent_id'] == $id)
        {
            $value['children'] = parentSons($value['id'],$data);
            unset($value['parent_id']);
            $sons[] = $value;
            unset($data[$key]);
        }
    }
    return $sons;
}

/**
 * 成功的响应
 * @param $arr
 * @param null $msg
 * @return \Illuminate\Http\JsonResponse
 */
function getSuccessResponse($arr,$msg=null)
{
    $ret = ['status'=> 0,
        'data'=>$arr,
        'msg'=> empty($msg)? '操作成功':$msg,
    ];

    return response()->json($ret);
}

/**
 * 失败的响应
 * @param $code
 * @param null $msg
 * @param null $data
 * @return \Illuminate\Http\JsonResponse
 */
function getErrorResponse($code,$msg=null,$data=null)
{
    if($msg==null) {
        $msg = config('code_msg.'.$code);
    }

    $ret = ['status'=>$code,
        'msg'=>$msg
    ];

    if(!is_null($data)){
        $ret['data']=$data;
    } else {
        $ret['data'] = new \stdClass();
    }

    return response()->json($ret);
}

/**
 * @param $code
 * @param string $msg
 * @throws \App\Exceptions\ResponseException
 */
function throwResponseException($code, $msg=''){
    throw new \App\Exceptions\ResponseException($code, $msg);
}

function runInTransaction($func){
    $ret = [];
    DB::beginTransaction();
    try {
        $ret = $func();
        DB::commit();
    } catch (\Exception $e) {
        DB::rollBack();
        throwResponseException($e->getCode(), $e->getMessage());
    }

    return $ret;
}

function http_post_json($url,$payload=null,$header=null){
    $response = Requests::post($url,$header,$payload);
    if($response->success){
        \Illuminate\Support\Facades\Log::debug('Http request ',['request'=>$url,'status_coe'=>$response->status_code,"body"=>$response->body]);
        return json_decode($response->body,True);
    }else{
        \Illuminate\Support\Facades\Log::error('Http request error!',['request'=>$url,'post'=>$payload,'status_coe'=>$response->status_code,"body"=>$response->body]);
        return [];
    }
}

function http_put_json($url,$payload=null,$header=null){
    $response = Requests::put($url,$header,$payload);
    if($response->success){
        return json_decode($response->body,True);
    }else{
        \Illuminate\Support\Facades\Log::error('Http request error!',['request'=>$url,'put'=>$payload,'status_coe'=>$response->status_code,"body"=>$response->body]);
        return [];
    }
}

function http_get_json($url, $header=null){
    $response = Requests::get($url, $header);

    if($response->success) {
        return $response->body;
    } else{
        return [];
    }
}

function http_delete_json($url,$payload=null,$header=null){
    $response = Requests::delete($url,$header,$payload);
    if($response->success){
        return json_decode($response->body,True);
    }else{
        return [];
    }
}

/**
 * 讲数组转化成对象
 * @param $arrList
 * @param $key
 * @param bool $append
 * @return array
 */
function arrToMap($arrList, $key, $append = false)
{
    $newArr = [];

    foreach ($arrList as $arr) {
        if ($append) {
            $newArr[$arr[$key]][] = $arr;
        } else {
            $newArr[$arr[$key]] = $arr;
        }
    }

    return $newArr;
}


/**
 * 返回可读性更好的文件尺寸
 */
function human_filesize($bytes, $decimals = 2)
{
    $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB'];
    $factor = floor((strlen($bytes) - 1) / 3);

    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) .@$size[$factor];
}

/**
 * 判断文件的MIME类型是否为图片
 */
function is_image($mimeType)
{
    return starts_with($mimeType, 'image/');
}
